import os
import subprocess

class MP4toHLSConverter:
    """Class for converting MP4 video to HLS format."""

    def __init__(self, input_file, output_dir='', resolutions=[]):
        """
        Initialize MP4toHLSConverter object.

        Parameters:
            input_file (str): The path to the input MP4 video file.
            output_dir (str, optional): The directory to save the converted HLS files. If not provided, a directory with the same name as the input file will be created.
            resolutions (list, optional): A list of resolutions for the HLS streams.
        """
        self.input_file = input_file
        self.output_dir = output_dir
        self.resolutions = resolutions

    def convert(self):
        """
        Convert MP4 video to HLS format.

        Returns:
            str: The path to the master playlist file.
        """
        # Get base name of input file without extension
        base_name = os.path.splitext(os.path.basename(self.input_file))[0]

        # Create output directory with base name of input file if it doesn't exist
        if not self.output_dir:
            self.output_dir = f"{base_name}"
        os.makedirs(self.output_dir, exist_ok=True)

        # Create a list to store the file paths for all the HLS playlists
        hls_file_paths = []

        for resolution in self.resolutions:
            # Construct output file name for HLS playlist
            output_playlist = f"{self.output_dir}/{base_name}-{resolution}.m3u8"

            # FFmpeg command to convert MP4 to HLS
            ffmpeg_cmd = f"ffmpeg -i {self.input_file} -threads 0 -preset fast -movflags faststart -profile:v baseline -level 3.0 -s {resolution} -start_number 0 -hls_time 10 -hls_list_size 0 -f hls {output_playlist}"

            try:
                # Call FFmpeg command using subprocess and get output
                process = subprocess.run(ffmpeg_cmd, shell=True, check=True, capture_output=True, text=True)

                # Add the file path of the generated HLS playlist to the list
                hls_file_paths.append(output_playlist)

            except subprocess.CalledProcessError as e:
                # Print error message
                print(f"FFmpeg command failed with error: {e.stderr}")
                return None

        # Write a master playlist file to reference all the HLS playlists
        master_playlist_path = f"{self.output_dir}/master.m3u8"

        try:
            with open(master_playlist_path, "w") as master_playlist_file:
                # Write the header for the master playlist file
                master_playlist_file.write("#EXTM3U\n")

                for i, hls_file_path in enumerate(hls_file_paths):
                    # Write the header for each HLS playlist
                    bandwidth = 1000000  # set bandwidth
                    master_playlist_file.write(f"#EXT-X-STREAM-INF:BANDWIDTH={bandwidth},RESOLUTION={self.resolutions[i]}\n")

                    # Write the path to the HLS playlist
                    master_playlist_file.write(f"{hls_file_path}\n")

        except Exception as e:
            # Print error message
            print(f"Failed to write master playlist file with error: {str(e)}")
            return None

        return master_playlist_path
